package com.cy.module.dingtalk.pc;

import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.Account;
import com.cy.model.Distributor;
import com.cy.model.Site;
import com.cy.model.SiteMapDevice;
import com.cy.module.WebApiController;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.commons.lang.StringUtils;

import java.util.List;

@ControllerBind(controllerKey = "/clmp/dingtalk/pc/distributor")
public class DistributorController extends WebApiController {

    @Override
    public void index() {
        Distributor distributor = getModel(Distributor.class);
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Page<Distributor> distributorPage = Distributor.dao.paginate(page, pageSize, Distributor.SELECT_ALL, distributor);
        for (Distributor temp : distributorPage.getList()){
            temp.put("account", temp.getAccount());
        }
        renderBuiPage(distributorPage, 200);
    }

    @Override
    public void update() {
       String account = getPara("account");
       Account tempAccount = null;
       if (StringUtils.isNotBlank(account)){
           tempAccount = Account.dao.getByAccount(account);
           if (tempAccount == null){
               renderFail("账号不存在");
               return;
           }
       }

       int id = getParaToInt();
       Distributor tempDistributor = getModel(Distributor.class);
       Distributor distributor = Distributor.dao.findById(id);
       distributor.coverExclude(tempDistributor, null);
       if (tempAccount != null)
           distributor.setAccountId(tempAccount.getAccountId());
       if (distributor.update()) {
           renderSuccess();
       } else {
           renderFail();
       }
    }

    @Override
    public void save() {
        String account = getPara("account");
        Account tempAccount = null;
        if (StringUtils.isNotBlank(account)){
            tempAccount = Account.dao.getByAccount(account);
            if (tempAccount == null){
                renderFail("账号不存在");
                return;
            }
        }
        Distributor distributor = getModel(Distributor.class);
        if (tempAccount != null)
            distributor.setAccountId(tempAccount.getAccountId());
        if (distributor.save()) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    @Override
    @Before(Tx.class)
    public void delete() {
        String[] ids = getPara().split("-");
        for (String id : ids){
            List<Site> sites = Site.dao.findByDistributor(Long.valueOf(id));
            for (Site site : sites){
                SiteMapDevice.dao.deleteBatch("site_id", site.getId());
            }
        }
        Site.dao.deleteBatch("distributor_id", ids);
        Distributor.dao.deleteBatch("id", ids);
        renderSuccess();
    }

}